/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.aop.asm;

import cn.easyplatform.org.objectweb.asm.MethodVisitor;
import cn.easyplatform.org.objectweb.asm.Opcodes;
import cn.easyplatform.org.objectweb.asm.Type;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a>
 */
abstract class NormalMethodAdapter {

	final String desc;

	final int access;

	final MethodVisitor mv;

	/**
	 * Argument types of the method visited by this adapter.
	 */
	final Type[] argumentTypes;

	NormalMethodAdapter(MethodVisitor mv, String desc, int access) {
		this.mv = mv;
		this.desc = desc;
		this.access = access;
		argumentTypes = Type.getArgumentTypes(this.desc);
	}

	abstract void visitCode();

	/**
	 * Generates the instructions to load all the method arguments on the stack.
	 */
	void loadArgs() {
		loadArgs(0, argumentTypes.length);
	}

	void loadArgs(final int arg, final int count) {
		int index = 1;
		for (int i = 0; i < count; ++i) {
			Type t = argumentTypes[arg + i];
			loadInsn(t, index);
			index += t.getSize();
		}
	}

	/**
	 * Generates the instruction to push a local variable on the stack.
	 * 
	 * @param type
	 *            the type of the local variable to be loaded.
	 * @param index
	 *            an index in the frame's local variables array.
	 */
	void loadInsn(final Type type, final int index) {
		mv.visitVarInsn(type.getOpcode(Opcodes.ILOAD), index);
	}

}
